<template>
    <div>
        <a-modal :visible="value" title="" :width="840">
            <div
                id="img-edit-box-container"
                class="content-box"
                v-if="contentType"
            >
                <div class="title">{{ title }}</div>
                <div class="content">
                    &nbsp;&nbsp; &nbsp;&nbsp;兹授权{{ grant }}全权代表<span
                        class="content-t"
                        >{{ companyName }}</span
                    >与{{ other }}。
                </div>
                <div class="content">
                    &nbsp;&nbsp; &nbsp;&nbsp;以上授权自盖章之日起生效，有效期为
                    <span class="content-t">{{ canYear }}</span>
                    年。如需取消授权，提前一个月书面通知。在本授权到期前十五日内，如双方无异议，则本授权合作期自动顺延一年，顺延次数不限。
                </div>
                <div class="gz">授权方 (盖章)：</div>
                <div class="sj">
                    日期：<span class="data-y">{{ year }}</span
                    >年<span class="data-s">{{ mon }}</span
                    >月<span class="data-s">{{ day }}</span
                    >日
                </div>
                <canvas id="canvas" width="163" height="163"></canvas>
            </div>
            <button @click="contentType = !contentType">关掉</button>
            <button @click="save">保存</button>
            <button @click="set">改公司名</button>
            <img
                style="width: 100px"
                v-for="(item, index) in showImgArr"
                :src="item.url"
                :alt="item.name"
                :key="index"
            />
            <div class="excel-reader">
                <a-upload
                    name="avatar"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :before-upload="handleBeforeUpload"
                >
                    <a-button title="读取Excel">
                        <a-icon type="file-excel" /> Excel Reader
                    </a-button>
                </a-upload>
            </div>
        </a-modal>
    </div>
</template>

<script>
import html2canvas from "html2canvas";
var XLSX = require("xlsx");
import { readFile } from "./excelRreadFile.js"; //读取excel文件方法

const DESC_OBJ = {
    广州恒萃信息科技有限公司: {
        title: "5G消息业务授权委托书",
        grant: "广州恒萃信息科技有限公司",
        other: "中国移动、中国联通、中国电信开通5G消息业务,本授权书不可以转授权",
    },
    彩讯科技股份有限公司: {
        title: "5G消息/视频短信业务授权委托书",
        grant: "彩讯科技股份有限公司",
        other: "中国移动、中国联通、中国电信开通5G消息业务、视频短信,本授权书不可以转授权",
    },
    广州瑞联讯信息科技有限公司: {
        title: "5G消息/视频短信业务授权委托书",
        grant: "广州瑞联讯信息科技有限公司",
        other: "中国移动、中国联通、中国电信开通5G消息业务、视频短信,本授权书不可以转授权",
    },
};

export default {
    props: {
        value: Boolean,
    },
    data() {
        return {
            contentType: true,
            companyName: "北京抖音信息服务有限公司",
            canYear: "二",
            showImgArr: [],
            year: "",
            mon: "",
            day: "",
            title: DESC_OBJ["广州恒萃信息科技有限公司"].title,
            grant: DESC_OBJ["广州恒萃信息科技有限公司"].grant,
            other: DESC_OBJ["广州恒萃信息科技有限公司"].other,
        };
    },
    created() {
        const newData = new Date();
        this.year = newData.getFullYear();
        this.mon = newData.getMonth() + 1;
        this.day = newData.getDay();
    },
    mounted() {
        this.companyNameArr = [
            "北京抖音信息服务有限公司",
            "广东省广播电视网络股份有限公司佛山分公司",
            "神州租车服务管理（福建）有限公司广州分公司",
            "佛山市禅城区祖庙街道同华社区居民委员会工会委员会",
            "深圳市绿景房地产开发有限公司佐阾香颂分公司",
        ];
        this.arr = [];
        this.index = 0;
        this.$nextTick(() => {
            this.gz();
        });
    },
    methods: {
        async handleBeforeUpload(file) {
            //选择文件后
            let _this = this;

            //选择excel文件后，并读取其内容（文件流）
            let dataBinary = await readFile(file);
            if (dataBinary != null) {
                // 将整个文件以二进制形式读取
                let workBook = XLSX.read(dataBinary, {
                    type: "binary",
                    cellDates: true,
                });

                // 工作表数量
                let workBookLen = workBook.SheetNames.length;

                // excel工作簿内容
                let excelBook = [];

                //读取每个sheets表
                for (let i = 0; i < workBookLen; i++) {
                    let workSheet = workBook.Sheets[workBook.SheetNames[i]];
                    excelBook.push({
                        sheetName: workBook.SheetNames[i],
                        data: XLSX.utils.sheet_to_json(workSheet, {
                            defval: null, //单元格为空时的默认值
                            raw: false, //使用w的值而不是v
                            dateNF: "yyyy-MM-dd", //日期格式
                        }),
                    });
                }
                const obj = {
                    name: file.name,
                    length: workBookLen,
                    data: excelBook,
                };
                console.log(obj.data[0]);
            }
        },
        base64toFile(base64Str, fileName) {
            let arr = base64Str.split(",");
            let mime = arr[0].match(/:(.*?);/)[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], fileName, { type: mime });
        },
        set() {
            this.companyName = this.companyNameArr[this.index];
            this.contentType = false;
            this.$nextTick(() => {
                this.contentType = true;
                this.$nextTick(() => {
                    this.gz(() => {
                        this.save(() => {
                            this.index++;
                            if (this.companyNameArr[this.index]) {
                                this.set();
                            } else {
                                this.index = 0;
                                this.arr.forEach((element) => {
                                    console.log(element);
                                    console.log(
                                        this.base64toFile(
                                            element.url,
                                            element.name
                                        )
                                    );
                                    this.showImgArr.push({
                                        name: element.name,
                                        url: element.url,
                                        file: this.base64toFile(
                                            element.url,
                                            element.name
                                        ),
                                    });
                                    var a = document.createElement("a"); //新建一个a链接
                                    a.setAttribute("href", element.url); // a链接的url为图片的url
                                    a.setAttribute("download", element.name);
                                    a.setAttribute("target", "_blank");
                                    let clickEvent =
                                        document.createEvent("MouseEvents");
                                    clickEvent.initEvent("click", true, true);
                                    a.dispatchEvent(clickEvent);
                                });
                            }
                        });
                    });
                });
            });
        },
        save(cb) {
            this.$nextTick(() => {
                html2canvas(document.querySelector("#img-edit-box-container"), {
                    backgroundColor: null,
                    useCORS: true, // Whether to attempt to load images from a server using CORS
                    allowTaint: true, // 是否允许跨源图像污染画布
                }).then((canvas) => {
                    const url = canvas.toDataURL("image/png");
                    this.arr.push({
                        url,
                        name: this.companyNameArr[this.index],
                    });
                    if (cb) cb();
                    // if (cb) cb(url);
                    // var a = document.createElement("a"); //新建一个a链接
                    // a.setAttribute("href", url); // a链接的url为图片的url
                    // a.setAttribute("download", name);
                    // a.setAttribute("target", "_blank");
                    // let clickEvent = document.createEvent("MouseEvents");
                    // clickEvent.initEvent("click", true, true);
                    // a.dispatchEvent(clickEvent);
                });
            });
        },
        gz(cb) {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            //绘制五角星
            function create5star(context, sx, sy, radius, color, rotato) {
                context.save();
                context.fillStyle = color;
                context.translate(sx, sy); //移动坐标原点
                context.rotate(Math.PI + rotato); //旋转
                context.beginPath(); //创建路径
                var x = Math.sin(0);
                var y = Math.cos(0);
                var dig = (Math.PI / 5) * 4;
                for (var i = 0; i < 5; i++) {
                    //画五角星的五条边
                    var x = Math.sin(i * dig);
                    var y = Math.cos(i * dig);
                    context.lineTo(x * radius, y * radius);
                }
                context.closePath();
                context.stroke();
                context.fill();
                context.restore();
            }
            var fontSize = 22; // 字体大小
            var angle1 = 4; // 字体修改后的旋转矫正
            var angle2 = 3; // 字体修改后的旋转矫正
            var arc = 72;
            var mathPi = 6; // 旋转矫正
            // 12 6 4.5
            var text = "";
            var companyName = this.companyName;

            if (companyName.length > 12) {
                fontSize = 14;
                angle1 = 6;
                angle2 = 4.5;
            }

            if (companyName.length > 20) {
                fontSize = 14;
                angle1 = 22;
                angle2 = 13;
                mathPi = 7.5;
            }

            // 绘制印章边框
            var width = canvas.width / 2;
            var height = canvas.height / 2;

            context.lineWidth = 4;
            context.strokeStyle = "#ca2a1d";
            context.beginPath();
            context.arc(width, height, arc, 0, Math.PI * 2); //宽、高、半径(半径用来跳转外圈的大小)
            context.stroke();

            //画五角星
            create5star(context, width, height, 20, "#ca2a1d", 0);

            // 绘制印章名称
            context.font = "12px";
            context.textBaseline = "middle"; //设置文本的垂直对齐方式
            context.textAlign = "center"; //设置文本的水平对对齐方式
            context.lineWidth = 1;
            context.strokeStyle = "#ca2a1d";
            context.strokeText(text, width, height + 50);

            // 绘制印章单位
            context.translate(width, height); // 平移到此位置,
            context.font = `lighter ${fontSize}px 宋体`;
            var count = companyName.length; // 字数
            var angle = (angle1 * Math.PI) / (angle2 * (count - 1)); // 字间角度
            var chars = companyName.split("");
            var c;
            for (var i = 0; i < count; i++) {
                c = chars[i]; // 需要绘制的字符
                if (i == 0) {
                    context.rotate((5 * Math.PI) / mathPi);
                } else {
                    context.rotate(angle);
                }

                context.save();
                context.translate(56, 0); // 平移到此位置,此时字和x轴垂直，公司名称和最外圈的距离
                context.rotate(Math.PI / 2); // 旋转90度,让字平行于x轴
                context.strokeText(c, 0, 0); // 此点为字的中心点
                context.restore();
            }
            if (cb) cb();
        },
    },
};
</script>

<style scoped>
.content-box {
    width: 794px;
    background: white;
    padding: 40px 80px;
    font-family: "宋体";
    display: flex;
    flex-direction: column;
    position: relative;
    margin-bottom: 100px;
    background: white;
    height: 1123px;
    margin: 0 auto;
}
#canvas {
    position: absolute;
    bottom: 490px;
    right: 50px;
    opacity: 0.9;
}
.title {
    width: 100%;
    text-align: center;
    font-weight: bold;
    font-size: 24px;
    font-family: "宋体";
    color: black;
    margin-bottom: 60px;
    margin-top: 100px;
}
.content {
    font-size: 20px;
    margin-bottom: 10px;
    font-family: "仿宋";
    color: black;
    letter-spacing: 1.5;
}
.content-t {
    text-decoration: underline;
}
.gz {
    margin-top: 100px;
    text-align: right;
    width: 100%;
    font-family: "仿宋";
    font-size: 20px;
    padding-right: 88px;
    color: black;
}
.sj {
    text-align: right;
    width: 100%;
    padding-right: 0px;
    font-family: "仿宋";
    font-size: 20px;
    margin-top: 10px;
    color: black;
}
.data-y {
    display: inline-block;
    width: 60px;
    text-align: center;
}
.data-s {
    display: inline-block;
    width: 30px;
    text-align: center;
}
</style>
